package com.qigao.mall.web.controller.app.user;

import com.alibaba.fastjson.JSONObject;
import com.qigao.mall.api.PayService;
import com.qigao.mall.commons.dto.MerProductResultDto;
import com.qigao.mall.commons.dto.PayCreateDto;
import com.qigao.mall.commons.enums.*;
import com.qigao.mall.commons.param.ChannelRespParam;
import com.qigao.mall.web.utils.RequestUtils;
import com.qigao.mall.web.vo.app.PayCreateVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

@Controller
@RequestMapping("/app/user/pay")
@Api(tags = "App支付相关API",value = "App支付相关API")
public class AppPayController {
    private static Logger logger= LoggerFactory.getLogger(AppPayController.class);
    @Resource
    PayService payService;

    //1.获取支付方式
    @ResponseBody
    @PostMapping("/findPayWayList/{shopNo}/{webSource}")
    @ApiOperation(value = "获取支付方式", notes = "获取支付方式")
    public Result<List> findPayWayList(@PathVariable("shopNo")String shopNo,@PathVariable("webSource")String webSource){
        try{
            //参数校验
            List<MerProductResultDto> merProductResultDtos=payService.findPayWayList(shopNo,webSource);
            if(merProductResultDtos!=null&&merProductResultDtos.size()>=1){
                return Result.newSuccess(merProductResultDtos);
            }else {
                return Result.newError(ResultCode.COMMON_DATA_NOT_EXISTS);
            }
        }catch (Exception e){
            logger.error("[获取支付方式]发生异常:{}",e);
            return Result.newError(ResultCode.FAIL);
        }
    }
    //2.发起支付请求 默认是微信小程序支付
    @ResponseBody
    @PostMapping("/goPay/{orderNo}")
    @ApiOperation(value = "发起支付请求", notes = "发起支付请求 ")
    public void goPay(@PathVariable("orderNo")String orderNo, HttpServletRequest request,HttpServletResponse response){
        PayCreateVo payCreateVo=new PayCreateVo();
        payCreateVo.setOrderNo(orderNo);
        payCreateVo.setPayWay(PayWayEnum.WEICHAT);
        payCreateVo.setWebSource(WebSourceEnum.WEICHAT_JSAPI);
        startPay(payCreateVo,request,response);
    }

    /**
     * 带支付方式的
     * @param payCreateVo
     * @param request
     * @return
     */
    @GetMapping("/startPay")
    @ApiOperation(value = "发起支付请求", notes = "发起支付请求 带支付方式")
    public void startPay(PayCreateVo payCreateVo, HttpServletRequest request, HttpServletResponse response)  {
        String retStr="00";
        try{
            //参数校验
            response.setContentType("application/Json;charset=UTF-8");
            PayCreateDto payCreateDto=new PayCreateDto();
            payCreateDto.setOrderNo(payCreateVo.getOrderNo());
            String payWayCode=payCreateVo.getPayWay().getPayWayCode();
            payCreateDto.setPayWay(payWayCode);
            String webSource=payCreateVo.getWebSource().getCode();
            payCreateDto.setWebSource(webSource);
            payCreateDto.setPayUserNo(RequestUtils.getCurrentUserNo(request));
            payCreateDto.setReqTermIp(RequestUtils.getReqIp(request));
            payCreateDto.setOpenId(RequestUtils.getCurrentUserNo(request));
            Result payResult= payService.createPayOrder(payCreateDto);
            retStr =  JSONObject.toJSONString(Result.newError(ResultCode.CHANNEL_ERROR));
            if(payResult.isSuccess()){
                ChannelRespParam channelRespParam=(ChannelRespParam)payResult.getData();
                if(ChannelCodeEnum.SUCCESS.getCode().equals(channelRespParam.getRespCode())){
                    //需要返回json对象
                    String respContent=channelRespParam.getRespContent();
                    if(StreamFormatEnum.JSON.equals(channelRespParam.getFormatEnum())){
                        JSONObject payJsonResult=JSONObject.parseObject(respContent);
                        retStr = JSONObject.toJSONString(Result.newSuccess(payJsonResult));
                    }else if(StreamFormatEnum.STREAM.equals(channelRespParam.getFormatEnum())){
                        response.setContentType("text/html;charset=UTF-8");
                        retStr=respContent;
                    }
                }else{
                    retStr =  JSONObject.toJSONString(Result.newError(ResultCode.CHANNEL_ERROR.getCode(),channelRespParam.getRespMsg()));
                }
            }
        }catch (Exception e){
            logger.error("[发起支付]发生异常:{}",e);
            retStr =   JSONObject.toJSONString(Result.newError(ResultCode.FAIL));
        }
        PrintWriter out = null;
        try {
            out = response.getWriter();
        } catch (IOException e) {
            logger.error("[发起支付]流信息输出异常:{}",e);
        }
        out.print(retStr);
        out.flush();
        out.close();
    }

}
